#include "datamaintenance.h"
#include "../utils/logger.h"
#include <QDateTime>

DataMaintenance::DataMaintenance(DBManager *dbManager, QObject *parent)
    : QObject(parent),
      m_dbManager(dbManager),
      m_historyRetentionDays(90),
      m_alarmRetentionDays(180)
{
    m_maintenanceTimer = new QTimer(this);
    connect(m_maintenanceTimer, &QTimer::timeout, this, &DataMaintenance::onTimedMaintenance);

    LOG_INFO("数据维护管理器初始化完成");
}

DataMaintenance::~DataMaintenance()
{
    stopAutoMaintenance();
}

void DataMaintenance::startAutoMaintenance(int checkIntervalHours)
{
    if (checkIntervalHours <= 0)
    {
        LOG_WARNING("维护检查间隔必须大于0小时");
        return;
    }

    // 转换为毫秒
    int intervalMs = checkIntervalHours * 60 * 60 * 1000;
    m_maintenanceTimer->setInterval(intervalMs);
    m_maintenanceTimer->start();

    LOG_INFO(QString("自动数据维护已启动，间隔: %1 小时").arg(checkIntervalHours));

    // 立即执行一次维护
    performMaintenance();
}

void DataMaintenance::stopAutoMaintenance()
{
    if (m_maintenanceTimer->isActive())
    {
        m_maintenanceTimer->stop();
        LOG_INFO("自动数据维护已停止");
    }
}

void DataMaintenance::performMaintenance()
{
    if (!m_dbManager || !m_dbManager->isConnected())
    {
        LOG_ERROR("数据库未连接，无法执行维护");
        return;
    }

    LOG_INFO("========== 开始数据维护 ==========");

    int deletedHistoryCount = 0;
    int deletedAlarmCount = 0;

    // 1. 清理过期历史数据
    if (m_historyRetentionDays > 0)
    {
        QDateTime cutoffTime = QDateTime::currentDateTime().addDays(-m_historyRetentionDays);
        deletedHistoryCount = m_dbManager->deleteHistoryData(QDateTime::fromSecsSinceEpoch(0), cutoffTime);

        if (deletedHistoryCount > 0)
        {
            LOG_INFO(QString("清理了 %1 条超过 %2 天的历史数据")
                         .arg(deletedHistoryCount)
                         .arg(m_historyRetentionDays));
        }
        else
        {
            LOG_INFO(QString("没有需要清理的历史数据（保留 %1 天）").arg(m_historyRetentionDays));
        }
    }

    // 2. 清理过期报警记录（这里暂不实现，需要在DBManager中添加对应方法）
    // 注意：报警记录通常需要保留更久，或者只清理已确认的旧记录
    LOG_INFO("报警记录保留策略：保留所有记录（未实现自动清理）");

    // 3. 优化数据库
    if (deletedHistoryCount > 1000)
    {
        LOG_INFO("数据量较大，执行数据库优化...");
        bool optimized = m_dbManager->optimizeDatabase();
        if (optimized)
        {
            LOG_INFO("数据库优化完成");
        }
        else
        {
            LOG_WARNING("数据库优化失败");
        }
    }

    // 4. 输出数据库统计信息
    int totalHistory = m_dbManager->getTableRowCount("history_data");
    int totalAlarms = m_dbManager->getTableRowCount("alarm_records");
    qint64 dbSize = m_dbManager->getDatabaseSize();

    LOG_INFO(QString("数据库统计: 历史数据=%1条, 报警记录=%2条, 数据库大小=%3 MB")
                 .arg(totalHistory)
                 .arg(totalAlarms)
                 .arg(dbSize / 1024.0 / 1024.0, 0, 'f', 2));

    LOG_INFO("========== 数据维护完成 ==========");

    emit maintenanceCompleted(deletedHistoryCount, deletedAlarmCount);
}

void DataMaintenance::onTimedMaintenance()
{
    LOG_INFO("触发定时数据维护");
    performMaintenance();
}
